package vip.liux.contracts.infrastructure.websocket;


import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistration;
import org.springframework.web.socket.server.HandshakeInterceptor;

@EnableWebSocket
@AutoConfiguration
public class WebSocketAutoConfiguration {

    public static final String PATH = "/ws";

    @Bean
    public WebSocketConfigurer webSocketConfigurer(
            ObjectProvider<HandshakeInterceptor> handshakeInterceptors,
            ObjectProvider<WebSocketHandler> webSocketHandler) {
        return registry -> webSocketHandler.ifAvailable(w -> {
                    // 添加 WebSocketHandler
                    WebSocketHandlerRegistration handlerRegistration = registry.addHandler(w);
                    // 添加握手拦截器
                    handshakeInterceptors.stream().forEach(handlerRegistration::addInterceptors);
                    handlerRegistration.setAllowedOriginPatterns("*");
                }
        );
    }
}
